package com.wyj.demo.common.websocket

import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.custom.util.LogStr
import com.custom.util.RxBus
import com.custom.util.openActivity
import com.wyj.demo.common.event.SendMessage
import com.wyj.demo.ui.activity.MainActivity
import java.net.URI

class WsService : Service() {
    var miWebSocket: WsClient? = null
    var wsURL: String = "ws://127.0.0.1:9090/socket"
    override fun onCreate() {
        super.onCreate()
        LogStr("onCreate")
        val uri = URI.create(wsURL)
        miWebSocket = WsClient(uri)
        miWebSocket?.connectBlocking()
        miWebSocket?.send("发送消息...")
        RxBus.send(SendMessage("发送消息成功"))
        openActivity(MainActivity::class.java)
        RxBus.send(SendMessage("返回消息，服务启动 onCreate"))
    }

    override fun onBind(p0: Intent?): IBinder? {
        LogStr("onBind")
        return null
    }

    //    用来描述系统在杀掉服务后是否要继续启动服务，START_STICKY表示如果Service进程被kill掉，系统会尝试重新创建Service。
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
        startService(Intent(this, WsService::class.java))
    }
}